package com.example.test.springdemo.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.test.springdemo.domain.AdminUser;
import com.example.test.springdemo.service.LoginService;
import com.example.test.springdemo.util.JWTUtils;
import com.example.test.springdemo.util.RemortIPUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：吉金武
 * @ClassName HandlerInterceptor
 * @date ：2022/1/18 - 23:48
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 * @description:
 * 拦截器
 **/
//@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map = new HashMap<>();
        String token = request.getHeader("token");
        System.out.println(token);
        try {
            JWTUtils.verify(token);
            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("message","无效签名");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("message","token已过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("message","token算法不一致");
        }catch (Exception e){
            e.printStackTrace();
            map.put("message","token无效");
        }
        map.put("code",50008);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}

